import 'dart:async';

import 'package:flutter/material.dart';
// import 'package:english_words/english_words.dart';
import 'package:flutter/services.dart' show rootBundle;
// import 'dart:developer';

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/jsons/cacheConfig.json');
}

const bool isProduct = bool.fromEnvironment("dart.vm.product");

class Point {
  // 定义变量
  late int x;

  void getsize() {
    // ignore: avoid_print
    // print('x = $x');
  }
}

void main() {
  var onError = FlutterError.onError;
  FlutterError.onError = (FlutterErrorDetails details) {
    onError?.call(details);
    // ... 处理上报逻辑，此处是flutter自己捕获的异常
  };

  // ignore: avoid_print
  // print(isProduct);

  runZoned(() => runApp(const MyApp()),
      // 异常配置
      zoneSpecification: ZoneSpecification(
        // 捕获打印
        print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
          // ...收集日志
          // ...
          // 打印 此处可判断是否是debug模式下，如果是再打印
          parent.// print(zone, "Interceptor: $line");
        },
        // 捕获未处理的异步异常
        handleUncaughtError: (self, parent, zone, error, stackTrace) {
          parent.// print(zone, '${error.toString()} $stackTrace');
          // 处理异常
          // 。。。
        },
      ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
            seedColor: const Color.fromARGB(255, 66, 157, 218)),
        useMaterial3: true,
      ),
      routes: {
        "newpage": (context) => const NewPage("title222"),
        // "/": (context) => const MyHomePage(title: 'Flutter Demo Home Page')
      },
      home: const MyHomePage(title: 'APP Name'),
      onGenerateRoute: (settings) {
        return MaterialPageRoute(builder: (context) {
          // ignore: avoid_print
          // print('------------------${settings.name}----------');
          // if(true){
          //   return
          // }
          return const NewPage("title222");
        });
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _switchSelected = false;
  bool _checkboxSelected = false;
  late TextEditingController myController;
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _unameController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  // void _incrementCounter(int index) {
  //   setState(() {
  //     // ignore: avoid_print
  //     // print(index);
  //     _counter = index;
  //   });
  // }

  @override
  void initState() {
    super.initState();
    myController = TextEditingController(text: 'jjjjjj');
    myController.addListener(() {
      // ignore: avoid_print
      // print(myController.text);
    });
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the widget tree.
    // This also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Builder(builder: (context) {
          return IconButton(
            icon: const Icon(Icons.dashboard, color: Colors.white), //自定义图标
            onPressed: () {
              // 打开抽屉菜单
              Scaffold.of(context).openDrawer();
            },
          );
        }),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(
          widget.title,
          textAlign: TextAlign.left,
        ),
        actions: [IconButton(onPressed: () {}, icon: const Icon(Icons.share))],
        // bottom: const TabBar(tabs: [Icon(Icons.ac_unit)]),
      ),
      drawer: Container(
        color: Colors.pink,
        child: const Align(
          widthFactor: 3,
          heightFactor: 3,
          alignment: Alignment(1, 0),
          child: FlutterLogo(
            size: 60,
          ),
        ),
      ),
      body: Container(
        color: Colors.pink,
        child: const Align(
          widthFactor: 3,
          heightFactor: 3,
          alignment: Alignment(1, 0),
          child: FlutterLogo(
            size: 60,
          ),
        ),
      ),

      // DefaultTextStyle(
      //     style: const TextStyle(color: Colors.amber),
      //     child: ListView(
      //       // mainAxisAlignment: MainAxisAlignment.center,
      //       children: <Widget>[

      //         const Text(
      //           'You have pushed the button this many times:hhhhhh h u have pushed the button this many times:hhhhhh h   h hhhh',
      //           textAlign: TextAlign.center,
      //           maxLines: 2,
      //           overflow: TextOverflow.ellipsis,
      //         ),
      //         Text(
      //           '$_counter',
      //           style: Theme.of(context).textTheme.headlineMedium,
      //           textAlign: TextAlign.right,
      //         ),
      //         const Text.rich(TextSpan(children: [
      //           TextSpan(text: "home:"),
      //           TextSpan(
      //               text: "http://baodu.com",
      //               style: TextStyle(color: Colors.blue))
      //         ])),
      //         ElevatedButton(
      //             onPressed: () {
      //               var aa = {"kk": 33, "mm": "dfad"};
      //               // ignore: avoid_print
      //               // print(aa);
      //               // ignore: avoid_print
      //               // print(const Text('normal'));
      //               var point = Point();
      //               point.x = 1;
      //               point.getsize();
      //               // ignore: avoid_print
      //               // print(point.toString());
      //             },
      //             child: const Text('normal')),
      //         ElevatedButton.icon(
      //           label: Text("发送"),
      //           icon: Icon(Icons.send),
      //           onPressed: () {},
      //         ),
      //         Switch(
      //           value: _switchSelected, //当前状态
      //           onChanged: (value) {
      //             //重新构建页面
      //             setState(() {
      //               _switchSelected = value;
      //             });
      //           },
      //         ),
      //         Checkbox(
      //           value: _checkboxSelected,
      //           // tristate: true,
      //           activeColor: Colors.yellow, //选中时的颜色
      //           onChanged: (value) {
      //             setState(() {
      //               _checkboxSelected = value!;
      //             });
      //           },
      //         ),
      //         TextField(
      //           decoration: const InputDecoration(
      //               border: OutlineInputBorder(
      //                   borderSide: BorderSide(
      //                 width: 1,
      //                 color: Colors.pink,
      //               )),
      //               enabledBorder: OutlineInputBorder(
      //                   borderSide:
      //                       BorderSide(color: Color.fromRGBO(0, 0, 0, 0.1))),
      //               labelText: "用户名",
      //               hintText: "用户名或邮箱",
      //               prefixIcon: Icon(Icons.person)),
      //           controller: myController,
      //         ),
      //         TextFormField(
      //           initialValue: 'dfsdfas',
      //           decoration: const InputDecoration(
      //               labelText: "密码",
      //               hintText: "您的登录密码",
      //               prefixIcon: Icon(Icons.lock)),
      //           obscureText: true,
      //         ),
      //         Form(
      //             key: _formKey,
      //             autovalidateMode: AutovalidateMode.always,
      //             child: Column(
      //               children: [
      //                 TextFormField(
      //                   controller: _unameController,
      //                   validator: (v) {
      //                     return v!.trim().isNotEmpty ? null : "用户名不能为空";
      //                   },
      //                 ),
      //                 TextFormField(
      //                   controller: _pwdController,
      //                   validator: (v) {
      //                     // ignore: avoid_print
      //                     // print(v);
      //                     return v!.trim().length > 5 ? null : "密码必须6位以上";
      //                   },
      //                 )
      //               ],
      //             )),
      //         ElevatedButton(
      //             onPressed: () {
      //               if ((_formKey.currentState as FormState).validate()) {
      //                 //验证通过提交数据
      //                 // ignore: avoid_print
      //                 // print(_pwdController.text);
      //                 // ignore: avoid_print
      //                 // print(_unameController.text);
      //               }
      //             },
      //             child: const Text("提交")),
      //         SizedBox(
      //             height: 10,
      //             child: LinearProgressIndicator(
      //               backgroundColor: Colors.grey[200],
      //               valueColor: const AlwaysStoppedAnimation(Colors.blue),
      //               value: .5,
      //             )),
      //         Container(
      //             alignment: Alignment.topCenter,
      //             color: Colors.yellow,
      //             child: SizedBox(
      //                 height: 80,
      //                 width: 80,
      //                 child: CircularProgressIndicator(
      //                   backgroundColor: Colors.grey[200],
      //                   valueColor: const AlwaysStoppedAnimation(Colors.blue),
      //                   value: .5,
      //                 ))),
      //         ProgressRoute()
      //       ],
      //     )),

      floatingActionButton: ClipOval(
        child: FloatingActionButton(
          // clipBehavior: Clip.hardEdge,
          onPressed: () {},
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
      // bottomNavigationBar: BottomNavigationBar(
      //   // 底部导航
      //   items: <BottomNavigationBarItem>[
      //     BottomNavigationBarItem(icon: Icon(Icons.home), label: 'home'),
      //     BottomNavigationBarItem(
      //         icon: Icon(Icons.business), label: 'Business'),
      //     BottomNavigationBarItem(icon: Icon(Icons.school), label: 'School'),
      //   ],
      //   currentIndex: _counter,
      //   fixedColor: Colors.blue,
      //   onTap: (int i) {
      //     setState(() {
      //       _counter = i;
      //     });
      //   },
      // ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      // bottomNavigationBar: BottomAppBar(
      //   // clipBehavior: Clip.antiAlias,
      //   shape: CircularNotchedRectangle(),
      //   child: Container(
      //     height: 60,
      //     padding: const EdgeInsets.symmetric(horizontal: 10.00),
      //     color: Colors.grey,
      //     child: Text('It should has a notch on it :/ --->'),
      //   ),
      // ),
      bottomNavigationBar: BottomAppBar(
        clipBehavior: Clip.antiAliasWithSaveLayer,
        color: Colors.white,
        shape: CircularNotchedRectangle(),
        // shape: const CircularNotchedRectangle(), // 底部导航栏打一个圆形的洞
        child: Row(
          children: [
            IconButton(onPressed: () {}, icon: Icon(Icons.home)),
            //中间位置空出
            IconButton(
              icon: Icon(Icons.business),
              onPressed: () {},
            ),
          ],
          mainAxisAlignment: MainAxisAlignment.spaceAround, //均分底部导航栏横向空间
        ),
      ),
    );
  }
}

class ProgressRoute extends StatefulWidget {
  @override
  _ProgressRouteState createState() => _ProgressRouteState();
}

class _ProgressRouteState extends State<ProgressRoute>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;

  @override
  void initState() {
    //动画执行时间3秒
    _animationController = AnimationController(
      vsync: this, //注意State类需要混入SingleTickerProviderStateMixin（提供动画帧计时/触发器）
      duration: const Duration(seconds: 3),
    );
    _animationController.forward();
    _animationController.addListener(() => setState(() => {}));
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(16),
            child: LinearProgressIndicator(
              backgroundColor: Colors.grey[200],
              valueColor: ColorTween(begin: Colors.grey, end: Colors.blue)
                  .animate(_animationController), // 从灰色变成蓝色
              value: _animationController.value,
            ),
          )
        ],
      ),
    );
  }
}

class NewPage extends StatelessWidget {
  const NewPage(this.title, {super.key});
  final Object title;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title as String),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          // Text(WordPair.random().toString()),
          TextButton(
              onPressed: () async {
                // debugger(when: true);
                var res = await loadAsset();
                // debug// print(context.toString());
                // ignore: use_build_context_synchronously
                Navigator.pop(context, res);
              },
              child: const Text("返回上一页"))
        ],
      ),
    );
  }
}
